from MyTT import *
import akshare as ak
import numpy as np
import os
from datetime import datetime
from sqlalchemy import create_engine, distinct, or_, and_
import sqlite3
import backtrader as bt
import pymssql
from urllib.parse import quote_plus as urlquote
from configparser import ConfigParser

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

conf = ConfigParser()
conf.read('env.ini')

sqlserver = 'sqlserver_out'
host = conf.get(sqlserver, 'host')
port = conf.get(sqlserver, 'port')
user = conf.get(sqlserver, 'user')
password = conf.get(sqlserver, 'password')
db_name = conf.get(sqlserver, 'db')


def get_trade_info():
    sql1 = f"SELECT MIN(datetime)/10000 FROM STOCK_MIN_DATA WHERE code='000001'"
    r1 = exec_sql(sql1)
    date_int = r1[0][0]
    sql2 = f"SELECT * FROM TWO_PERIOD_BREAK_POOL WHERE trade_date>={date_int}"
    r2 = exec_sql(sql2)
    df = pd.DataFrame(r2, columns=['trade_date', 'code', 'value'])
    df.sort_values('trade_date', inplace=True, ignore_index=True)
    # print(df)
    return df


def exec_sql(sql):
    conn = pymssql.connect(host=host, port=port, user=user, password=password, database=db_name)
    cursor = conn.cursor()
    cursor.execute(sql)
    r = cursor.fetchall()
    cursor.close()
    conn.close()
    return r


def time_map(x):
    t = datetime.strptime(str(x), '%Y%m%d%H%M')
    return t


def get_data(stocks):
    stocks = stocks[:2]
    # stocks = ['001298', '603990', '603915', '603701', '603567']
    # stocks = ['603990']
    # print(stocks)
    stocks_str = ','.join(f"'{tok}'" for tok in stocks)
    sql = f"SELECT * FROM STOCK_MIN_DATA WHERE code in ({stocks_str})"
    r = exec_sql(sql)
    df = pd.DataFrame(r, columns=['code', 'datetime', 'close', 'open', 'low', 'high', 'volume', 'money'])
    df['datetime'] = df['datetime'].map(time_map)
    sql2 = f"SELECT COUNT(1) FROM STOCK_MIN_DATA WHERE code='000001'"
    r2 = exec_sql(sql2)
    test_count = r2[0][0]
    res = dict()

    for code in stocks:
        sig_df = df.loc[df['code'] == code]
        print(f'code={code}->len={len(sig_df)}->test_count={test_count}')
        if len(sig_df) == test_count or code == '000001':
            sig_df.sort_values('datetime', inplace=True, ignore_index=True)
            sig_df.set_index('datetime', inplace=True)
            res[code] = sig_df
            # print(res)
            # break

    return res


ratio = 0.05
code_info = dict()
count_info = dict()
code_high = dict()
code_line = dict()
buy_info = dict()
trade_info = get_trade_info()
stocks = trade_info['code'].unique()


def run_backtrade():
    cerebro = bt.Cerebro()

    all_data = get_data(stocks)

    for code in all_data:
        data = all_data[code]
        count_info[code] = 0
        df = trade_info.query(f"code=='{code}'")
        if len(df) > 0:
            for idx, row in df.iterrows():
                trade_date = row['trade_date']
                value = row['value']
                if code in code_info:
                    code_info[code][trade_date] = value
                else:
                    code_info[code] = {trade_date: value}

        datafeed = bt.feeds.PandasData(dataname=data)
        cerebro.adddata(datafeed, name=code)
        print(f'{code} feeds ok')

    # print(f'code_info={code_info}')
    print(f'stocks len={len(code_info)}')

    ##   st_date = datetime.datetime(2023, 3, 1)
    ##ed_date = datetime.datetime(2023, 6, 5)

    # 初始资金 100,000,0
    cerebro.broker.setcash(1000000.0)
    # 佣金，双边各 0.0003
    cerebro.broker.setcommission(commission=0.001)
    # 滑点：双边各 0.0001
    # cerebro.broker.set_slippage_perc(perc=0.005)

    cerebro.addanalyzer(bt.analyzers.TimeReturn, _name='pnl')  # 返回收益率时序数据
    cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name='_AnnualReturn')  # 年化收益率
    cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='_SharpeRatio')  # 夏普比率
    cerebro.addanalyzer(bt.analyzers.DrawDown, _name='_DrawDown')  # 回撤

    cerebro.addstrategy(TestStrategy)

    result = cerebro.run()
    strat = result[0]
    # 返回日度收益率序列
    daily_return = pd.Series(strat.analyzers.pnl.get_analysis())
    # 打印评价指标
    print("--------------- TimeReturn -----------------")
    print(daily_return)
    print("--------------- AnnualReturn -----------------")
    print(strat.analyzers._AnnualReturn.get_analysis())
    print("--------------- SharpeRatio -----------------")
    print(strat.analyzers._SharpeRatio.get_analysis())
    print("--------------- DrawDown -----------------")
    print(strat.analyzers._DrawDown.get_analysis())
    # cerebro.plot()


class TestStrategy(bt.Strategy):
    params = (('maperiod', 10), ('lb_v', 2.2), ('printlog', False),)

    def __init__(self):
        # 初始化交易指令
        self.order = None
        self.buy_list = []
        self.buy_stock = trade_info
        self.trade_dates = self.buy_stock['trade_date'].unique().tolist()
        self.order_list = []  # 记录以往订单，方便调仓日对未完成订单做处理
        self.buy_stocks_pre = []  # 记录上一期持仓
        self.lb = dict()

        for data in self.datas:
            self.lb[data] = bt.DivByZero(data.volume, bt.ind.SMA(data.volume, period=self.p.maperiod))

    def next(self):
        if self.order:  # 查看是否有指令执行，如果有则不执行这bar
            return

        # for code in set(self.getdatanames()) - set(self.buy_list):
        for data in self.datas:
            log_str = ""
            code = data._name
            data = self.getdatabyname(code)
            dt = data.datetime.date(0)  # 获取当前的回测时间点
            dt = int(dt.strftime('%Y%m%d'))

            self.log(f'code={code}->datetime {data.lines.datetime.datetime(0)}, close {data.close[0]}, 资产：{self.broker.getvalue()} 元')

            # print(f"-------------{code} next 的第{count_info[code] + 1}次循环 --------------")
            # print(f"今日：datetime {data.lines.datetime.date(0)} close {data.lines.close[0]}")
            print(
                f"code={code}->当前时点（今日）：datetime {data.lines.datetime.datetime(0)} close {data.lines.close[0]} high={data.lines.high[0]} open={data.lines.open[0]}->lb={self.lb[data][0]}")
            # log_str += f"-------------{code} next 的第{count_info[code] + 1}次循环 --------------\n"
            # log_str += f"今日：datetime {data.lines.datetime.date(0)} close {data.lines.close[0]}\n"
            # log_str += f"当前时点（今日）：datetime {data.lines.datetime.datetime(0)} close {data.lines.close[0]}->high={data.lines.high[0]}\n"

            if code in code_high and data.high > code_high[code]:
                # print(f"modify：datetime {data.lines.datetime.datetime(0)} pH={code_high[code]}->high={data.lines.high[0]}->lb={self.lb[data][0]}")
                # log_str += f"modify：datetime {data.lines.datetime.datetime(0)} pH={code_high[code]}->high={data.lines.high[0]}\n"
                code_high[code] = data.high[0]
                code_line[code] = (1 - ratio) * data.high[0]

            pos = self.getposition(data).size

            # log_str += f'lb={self.lb[data][0]}->lb1={self.lb1[data][0]}->lb2={self.lb2[data][0]}\n'

            if not pos:
                if (dt in code_info[code]) and (data.high > code_info[code][dt]) and (self.lb[data] > self.p.lb_v):
                    self.order = self.buy(data=data, size=100, name=code)
                    code_high[code] = data.high[0]
                    code_line[code] = (1 - ratio) * data.high[0]
                    buy_info[code] = dt
                    print(
                        f'code: {code} datetime {data.lines.datetime.datetime(0)} BUY,BUY,BUY!!! high={data.high[0]}->pro_high={code_info[code][dt]}->lb={self.lb[data][0]}')
                    # log_str += f'BUY,BUY,BUY!!! high={data.high[0]}->pro_high={code_info[code][dt]}->lb={self.lb[data][0]}\n'

            elif dt != buy_info[code] and data.low < code_line[code]:
                # data = self.getdatabyname(code)
                self.order = self.close(data=data, name=code)
                print(
                    f'code: {code} datetime {data.lines.datetime.datetime(0)} SELL,SELL,SELL!!! base={code_line[code]}->low={data.low[0]}->lb={self.lb[data][0]}')
                # log_str += f'SELL,SELL,SELL!!! base={code_line[code]}->low={data.low[0]}\n'

            # 在 next() 中调用 len(self.data0)，返回的是当前已处理（已回测）的数据长度，会随着回测的推进动态增长
            # print(f"已处理的数据点：{len(data)}")
            # log_str += f"已处理的数据点：{len(data)}\n"
            # buflen() 返回整条线的总长度，固定不变；
            # print(f"line的总长度：{data.buflen()}")
            # log_str += f"line的总长度：{data.buflen()}\n"

    def log(self, txt, dt=None, doprint=True):
        if self.params.printlog or doprint:
            dt = dt or self.datas[0].datetime.date(0)
            # print(f'{dt.isoformat()},{txt}')
            print(txt)

    def notify_order(self, order):
        # 未被处理的订单
        if order.status in [order.Submitted, order.Accepted]:
            return
        # 已经处理的订单
        if order.status in [order.Completed, order.Canceled, order.Margin]:
            if order.isbuy():
                self.log(
                    f'code={order.data._name} BUY CREATE TIME: {bt.num2date(order.created.dt)}, EXECUTED TIME: {bt.num2date(order.executed.dt)}')
                self.log(
                    'BUY EXECUTED, ref:%.0f，Price: %.2f, Cost: %.2f, Comm %.2f, Size: %.2f, Stock: %s' %
                    (order.ref,  # 订单编号
                     order.executed.price,  # 成交价
                     order.executed.value,  # 成交额
                     order.executed.comm,  # 佣金
                     order.executed.size,  # 成交量

                     order.data._name))  # 股票名称
            else:  # Sell
                self.log(
                    f'code={order.data._name} SELL CREATE TIME: {bt.num2date(order.created.dt)}, EXECUTED TIME: {bt.num2date(order.executed.dt)}')
                self.log('SELL EXECUTED, ref:%.0f, Price: %.2f, Cost: %.2f, Comm %.2f, Size: %.2f, Stock: %s' %
                         (order.ref,
                          order.executed.price,
                          order.executed.value,
                          order.executed.comm,
                          order.executed.size,
                          order.data._name))

            self.bar_executed = len(self)

        # Write down: no pending order
        self.order = None

    def stop(self):
        print('Strategy Finish!!!')


if __name__ == '__main__':
    run_backtrade()
